package com.lk.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.lk.mapper.TGpsDataMapper;
import com.lk.model.TGpsData;
import com.lk.utils.JdbcUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

@Slf4j
public class TGpsDataListener extends AnalysisEventListener<TGpsData> {
    /**
     * 每隔500条存储数据库，实际使用中可以1000条，然后清理list ，方便内存回收
     */
    @Autowired
    private TGpsDataMapper tGpsDataMapper;

    public TGpsDataListener(TGpsDataMapper tGpsDataMapper) {
        this.tGpsDataMapper = tGpsDataMapper;
    }

    private static final int BATCH_COUNT = 500;

    private List<TGpsData> cachedDataList = Lists.newArrayListWithExpectedSize(BATCH_COUNT);


    @Override
    public void invoke(TGpsData tGpsData, AnalysisContext context) {
        log.info("解析到一条数据:{}", JSON.toJSONString(tGpsData));
        cachedDataList.add(tGpsData);
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            cachedDataList = Lists.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
        log.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", cachedDataList.size());
        Long begin = System.currentTimeMillis();

        //tGpsDataMapper.insertBatch(cachedDataList);
        for (TGpsData tGpsData : cachedDataList) {
            tGpsDataMapper.insert(tGpsData);
        }

        // 结束时间
        Long end =System.currentTimeMillis();
        log.info("耗时 time : " + (end - begin) / 1000 + " s");
    }
}

